package com.eastfair.messagecenter.pending;

import com.eastfair.messagecenter.enumeration.ChannelType;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 存储 每种消息类型 与 TaskPending 的关系
 * 线程池
 * @author ligang
 */
@Component
public class TaskPendingHolder {
    //线程数量=内核*2
    private static int N_CPUS = Runtime.getRuntime().availableProcessors()*2;
    private Map<ChannelType, ExecutorService> taskPendingHolder = new HashMap<>(32);

    /**
     * 获取得到所有的groupId
     */
    private static ChannelType[] channelTypes = ChannelType.values();

    /**
     * 给每个渠道，每种消息类型初始化一个线程池
     */
    @PostConstruct
    public void init() {
        /**
         * example ThreadPoolName:austin.im.notice
         *
         * 可以通过apollo配置：dynamic-tp-apollo-dtp.yml  动态修改线程池的信息
         */
        for (ChannelType channelType : channelTypes) {
            ExecutorService executorService = Executors.newFixedThreadPool(N_CPUS);
            taskPendingHolder.put(channelType, executorService);
        }
    }

    /**
     * 得到对应的线程池
     *
     * @param sendChannel
     * @return
     */
    public ExecutorService route(ChannelType sendChannel) {
        return taskPendingHolder.get(sendChannel);
    }


}
